using System;
using System.Diagnostics;
using Mbs.Log;

namespace Mbs.ComponentModel
{
    /// <summary>
    /// Action stack
    /// </summary>
    class ActionStack
    {
        private const int DefaultMaxCount = 20;
        internal static readonly ILog _log = LoggerManager.GetLogger("Undo Manager");

        internal StackList<IUndoAction> undoStack;
        internal StackList<IUndoAction> redoStack;

        public ActionStack()
            : this(DefaultMaxCount)
        {
        }

        public ActionStack(int size)
        {
            undoStack = new StackList<IUndoAction>(size);
            redoStack = new StackList<IUndoAction>(size);
        }

        /// <summary>
        /// can undo 
        /// </summary>
        public bool CanUndo
        {
            get { return undoStack.Count > 0; }
        }

        /// <summary>
        /// can redo
        /// </summary>
        public bool CanRedo
        {
            get { return redoStack.Count > 0; }
        }

        public void Undo()
        {
            try
            {
                if (undoStack.Count > 0)
                {
                    IUndoAction action = undoStack.Pop();
                    redoStack.Push(action);
                    action.Undo();
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }
        }

        public void Redo()
        {
            try
            {
                if (redoStack.Count > 0)
                {
                    IUndoAction action = (IUndoAction)redoStack.Pop();
                    undoStack.Push(action);
                    action.Redo();
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }
        }

        public void Push(IUndoAction action)
        {
            Debug.Assert(action != null);

            try
            {
                undoStack.Push(action);
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
            }
        }

        public void ClearAll()
        {
            undoStack.Clear();
            redoStack.Clear();
        }

        public StackList<IUndoAction> UndoStack
        {
            get { return undoStack; }
        }
    }
}
